package com.diudiutechnology.www.yadiudiu.yadiudiu.main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diudiutechnology.www.yadiudiu.R;
import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.RedPacket;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.view.AutoVerticalScrollTextView;
import com.diudiutechnology.www.yadiudiu.util.view.GoodsDetailTimerView;
import com.diudiutechnology.www.yadiudiu.util.view.HorizontalListView;
import com.diudiutechnology.www.yadiudiu.util.view.ListViewForScrollView;
import com.diudiutechnology.www.yadiudiu.util.view.RedPacketTest;
import com.diudiutechnology.www.yadiudiu.util.view.RedRainPhotoPop;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.CommodityDetailsActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.HomePageSignActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyAdapter.HomePageAdapter;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyAdapter.HomePageHorizontalAdapter;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyAdapter.HomePageHorizontalWaveAdapter;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyAdapter.HomePageListViewAdapter;
import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyAdapter.BannersAdapter;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.BuyACarFragmentModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.HomePageModel;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/8/14.
 * 首页板块
 */

public class HomePageFragment extends LazyFragment implements View.OnClickListener,
        Callback.CommonCallback<String> {

    private static final String TAG = "HomePageFragment";

    RelativeLayout menu_layout;//红包雨页面

    HorizontalListView horizontalwaveListView;//红包时间

    HomePageHorizontalWaveAdapter homePageHorizontalWave;

    ListView listViewplay;//中奖人

    HomePageListViewAdapter adapter;

    List<BuyACarFragmentModel> listViewplaylistView;//中奖数据

    RedPacketTest red_packets_view;//红包雨

    AlertDialog.Builder alertDialog;//弹框

    GoodsDetailTimerView timerView;//倒计时

    ListViewForScrollView listViewForScrollView;//数据

    HomePageAdapter listViewAdapter;

    HorizontalListView horizontalListView;//秒杀时间

    HomePageHorizontalAdapter horizontalAdapter;

    LinearLayout title_right;//签到

    TextView city;//城市

    TextView yesterdayTurnover;//昨日成交金额

    TextView yesterdayConsumption;//昨日消费金额

    AutoVerticalScrollTextView taskcenter;//公告

    List<String> taskcenterlist;//公告list

    private boolean isRunning = true;

    private int number = 0;

    private ViewPager ad_pager;//轮播

    private LinearLayout ad_layer; // 圈圈 布局

    private final int HOME_AD_RESULT = 1;//轮播图

    private final int HOME_AD_NOTICE = 2;//广告

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case HOME_AD_RESULT://轮播图
                    ad_pager.setCurrentItem(ad_pager.getCurrentItem() + 1,
                            true);
                    break;
                case HOME_AD_NOTICE:// 广告
                    taskcenter.next();
                    number++;
                    taskcenter
                            .setText(taskcenterlist.get(number % taskcenterlist.size()).toString());

                    break;
            }
        }

        ;
    };

    private Context context;

    LinearLayout retur;//选择城市

    private View contentView;

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        super.onCreateViewLazy(savedInstanceState);
        contentView = View.inflate(context, R.layout.fragment_home_page, null);
        setContentView(contentView);
        initView();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();

    }

    private void initView() {
        alertDialog = new AlertDialog.Builder(context);
        taskcenter = (AutoVerticalScrollTextView) findViewById(R.id.taskcenter);
        timerView = (GoodsDetailTimerView) findViewById(R.id.timerView);
        menu_layout = (RelativeLayout) findViewById(R.id.menu_layout);
        red_packets_view = (RedPacketTest) findViewById(R.id.red_packets_view);
        listViewplay = (ListView) findViewById(R.id.listViewplay);
        title_right = (LinearLayout) findViewById(R.id.title_right);

        horizontalListView = (HorizontalListView) findViewById(R.id.horizontalListView);

        horizontalwaveListView = (HorizontalListView) findViewById(R.id.horizontalwaveListView);

        listViewForScrollView = (ListViewForScrollView) findViewById(R.id.listViewForScrollView);
        retur = (LinearLayout) findViewById(R.id.retur);

        ad_pager = (ViewPager) findViewById(R.id.ad_pager);
        ad_layer = (LinearLayout) findViewById(R.id.ad_layer);

        city = (TextView) findViewById(R.id.city);
        yesterdayTurnover = (TextView) findViewById(R.id.tv_yesterday_turnover);
        yesterdayConsumption = (TextView) findViewById(R.id.tv_yesterday_consumption);

        retur.setOnClickListener(this);
        title_right.setOnClickListener(this);

        initData();
    }

    public void initData() {
        //秒杀时间
        horizontalAdapter = new HomePageHorizontalAdapter(context);
        horizontalListView.setAdapter(horizontalAdapter);
        List<BuyACarFragmentModel> buycarlist = new ArrayList<>();

        //商品
        listViewAdapter = new HomePageAdapter(context);
        listViewForScrollView.setAdapter(listViewAdapter);

        listViewForScrollView.setOnItemClickListener(onItemClickListener);
        List<BuyACarFragmentModel> buycarScrollView = new ArrayList<>();

        //下红包雨时间
        homePageHorizontalWave = new HomePageHorizontalWaveAdapter(context);
        horizontalwaveListView.setAdapter(homePageHorizontalWave);
        List<BuyACarFragmentModel> list = new ArrayList<>();

        BuyACarFragmentModel modes = new BuyACarFragmentModel();
        modes.setName("东风标致4S店重庆店");
        list.add(modes);
        modes = new BuyACarFragmentModel();
        modes.setName("广汽传祺广汽传祺广汽传祺祺");

        list.add(modes);
        homePageHorizontalWave.addItem(list);

        //中奖人
        adapter = new HomePageListViewAdapter(context);
        listViewplay.setAdapter(adapter);
        listViewplaylistView = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            BuyACarFragmentModel mod = new BuyACarFragmentModel();
            mod.setName("东风标致4S店重庆店");
            listViewplaylistView.add(mod);
        }
        adapter.addItem(listViewplaylistView);
        listViewplay.setOnScrollListener(onScrollListener);
        listViewplay.setSelection(list.size());

        taskcenterlist = new ArrayList<>();
        taskcenter.setText("哈哈哈");
        HttpClient.homePage(this);
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            startActivity(new Intent(context, CommodityDetailsActivity.class));
        }
    };

    //轮播广告
    public void getadvertising(final int size, final List<String> getinforresult) {
        ad_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                Sundry.refreshPoint(ad_layer, position % size, 0);
                if (mHandler.hasMessages(HOME_AD_RESULT)) {
                    mHandler.removeMessages(HOME_AD_RESULT);
                }
                mHandler.sendEmptyMessageDelayed(HOME_AD_RESULT, 3 * 1000);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (ViewPager.SCROLL_STATE_DRAGGING == arg0
                        && mHandler.hasMessages(HOME_AD_RESULT)) {
                    mHandler.removeMessages(HOME_AD_RESULT);
                }
            }
        });
        BannersAdapter adapter = new BannersAdapter(context, getinforresult, 0);
        ad_pager.setAdapter(adapter);
        Sundry.initPointsLayout(ad_layer, context, size, 0);
        ad_pager.setCurrentItem(size * 1000, false);
        // 自动轮播线程
        mHandler.sendEmptyMessageDelayed(HOME_AD_RESULT, 3 * 1000);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
//                showSelectPicPop();
                startRedRain();
                menu_layout.setVisibility(View.VISIBLE);
                break;
            case R.id.title_right:
                startActivity(new Intent(context, HomePageSignActivity.class));
                break;

        }
    }

    /**
     * 开始下红包雨
     */
    private void startRedRain() {
        red_packets_view.startRain();
        red_packets_view.setOnRedPacketClickListener(new RedPacketTest.OnRedPacketClickListener() {
            @Override
            public void onRedPacketClickListener(RedPacket redPacket) {
                red_packets_view.pauseRain();
                alertDialog.setCancelable(false);
                alertDialog.setTitle("红包提醒");
                alertDialog.setNegativeButton("继续抢红包", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        red_packets_view.restartRain();
                    }
                });

                if (redPacket.isRealRed) {
                    alertDialog.setMessage("恭喜你，抢到了" + redPacket.money + "元！");
//                    totalmoney += redPacket.money;
//                    money.setText("中奖金额: " + totalmoney);
                } else {
                    alertDialog.setMessage("很遗憾，下次继续努力！");
                }
                red_packets_view.post(new Runnable() {
                    @Override
                    public void run() {
                        alertDialog.show();
                    }
                });
            }
        });
    }

    /**
     * 停止下红包雨
     */
    private void stopRedRain() {

        red_packets_view.stopRainNow();
    }

    //  OnScrollListener
    AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
            /**到顶部添加数据关键<span style="font-size:14px;">代码</span>*/
            if (firstVisibleItem <= 2) {
                listViewplay.setSelection(listViewplaylistView.size() + 2);
            } else if (firstVisibleItem + visibleItemCount > adapter.getCount() - 2) {//到底部添加数据
                listViewplay.setSelection(firstVisibleItem - listViewplaylistView.size());
            }
        }
    };

    private void showSelectPicPop() {
        RedRainPhotoPop redRainPhotoPop = new RedRainPhotoPop(context, this);
        redRainPhotoPop.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    //scrollview初始位置
    public void processscrollTo(String re) {
        city.setText(re);
    }

    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
        // city.setText(MyApplication.getInstance().getCity());
    }

    @Override
    public void onSuccess(String result) {
        Log.e(TAG, "onSuccess: " + result);
        HomePageModel homePage = JsonTools.getHomePage(result);
        Log.e(TAG, "onSuccess: " + homePage);
        int status = homePage.getStatus();
        String msg = homePage.getMsg();
        if (status == 200) {
            processdata(homePage);
        } else if (status == 105) {
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
            ToastUtils.show(context, msg);
        } else {
            ToastUtils.show(context, msg);
        }
    }

    private void processdata(HomePageModel homePage) {
        //设置banner轮播图
        List<HomePageModel.BannerBean> banner = homePage.getBanner();
        List<String> bannerImages = new ArrayList<>();
        for (int i = 0; i < banner.size(); i++) {
            HomePageModel.BannerBean bannerBean = banner.get(i);
            bannerImages.add(bannerBean.banner);
        }
        getadvertising(banner.size(), bannerImages);

        //昨日消费人数 昨日成交金额
        yesterdayConsumption.setText(String.valueOf(homePage.ConsumerPopulation));
        yesterdayTurnover.setText(homePage.TransactionAmount);

        //秒杀专场
        List<HomePageModel.SeckillTimeBean> seckillTime = homePage.getSeckillTime();
        horizontalAdapter.addItem(seckillTime);
        String countDown = seckillTime.get(0).countDown;
        String[] split = countDown.split(":");
        timerView.setOnTimeOutCallBack(new GoodsDetailTimerView.OnTimeOutCallBack() {
            @Override
            public void onCallBack() {
                //
                horizontalAdapter.removeItem(0);
                String countDown1 = horizontalAdapter.getDatas().get(0).getCountDown();
                String[] split = countDown1.split(":");
                timerView.setTime(0,
                        Integer.parseInt(split[0]),
                        Integer.parseInt(split[1]), Integer.parseInt(split[2]));// 设置时间(day,hour,min,sec)
                timerView.start();// 开始倒计时
            }
        });
        // 设置时间(day,hour,min,sec)
       /*timerView.setTime(0,
                   Integer.parseInt(split[0]),
                   Integer.parseInt(split[1]), Integer.parseInt(split[2]));*/
        timerView.setTime(0, 0, 10, 0);// 设置时间(day,hour,min,sec)
        timerView.start();// 开始倒计时
        //商品数据
        listViewAdapter.addItem(homePage.getGoods());
        //秒杀通知
        List<HomePageModel.OrderNoticeBean> notice = homePage.getOrderNotice();
        for (int i = 0; i < notice.size(); i++) {
            HomePageModel.OrderNoticeBean bean = notice.get(i);
            taskcenterlist.add(bean.getNickname() + " 成功抢得 - " + bean.getOrdername());

        }
        new Thread() {
            @Override
            public void run() {
                while (isRunning) {
                    SystemClock.sleep(Constant.LUNBO);
                    mHandler.sendEmptyMessage(HOME_AD_NOTICE);
                }
            }
        }.start();
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        Log.e(TAG, "onError: " + ex.toString());
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
}
